package controller

import (
	"fmt"
	"ginEssential/common"
	"ginEssential/dto"
	"ginEssential/model"
	"ginEssential/response"
	"log"
	"strconv"

	"github.com/gin-gonic/gin"
)

func AddCharacter(ctx *gin.Context) {

	DB := common.GetDB()

	nc := model.Character{}
	ctx.ShouldBind(&nc)
	name := nc.Name
	id := 1
	age := nc.Age

	newCharacter := model.Character{
		Name: name,
		Age:  age,
		// Id:   nil,
	}

	DB.Create(&newCharacter)

	log.Println(name, id, age)

	response.Success(ctx, nil, "添加成功")

}

func GetCharacter(ctx *gin.Context) {

	// p := ctx.Query("page")
	// l := ctx.Query("limit")
	// fmt.Println("page:", p)
	// fmt.Println("limit:", l)
	db := common.GetDB()
	var character []model.Character
	page, err := strconv.Atoi(ctx.Query("page"))
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	limit, err := strconv.Atoi(ctx.Query("limit"))
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	total := 0
	db.Raw("SELECT COUNT(*) table_schema FROM characters").Scan(&total)
	fmt.Println("total: ", total)
	db.Order("created_at desc").Limit(limit).Offset((page - 1) * limit).Find(&character)

	fmt.Println(character)
	res := dto.ToCharacterDto(character)
	m := make(map[string]interface{})
	m["code"] = 200
	m["data"] = res
	m["total"] = total
	ctx.JSON(200, m)
}
